package cn.cs.service.impl;

import cn.cs.client.*;
import cn.cs.common.*;
import cn.cs.pojo.RepairUser;
import cn.cs.service.AgentUserService;
import cn.cs.vo.TokenVO;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class AgentUserServiceImpl implements AgentUserService {
    @Resource
    private AgentUserClient agentUserClient;
    @Resource
    private AgentShopClient agentShopClient;
    @Resource
    private SysDtAreaClient sysDtAreaClient;
    @Resource
    private AgentUserForUserDB agentUserForUserDB;
    @Resource
    private AgentUserForShopDB agentUserForShopDB;
    @Resource
    private AgentUserForOrderDB agentUserForOrderDB;
    @Resource
    private RedisUtils redisUtils;
    @Resource
    private  RestRepairUserClient repairUserClient;
    @Override
    public Map<String, Object> getAgentUserByPhone(String phone) throws Exception{
        Map<String,Object> agentUser = agentUserClient.getAgentUserByPhone(phone);
        Map<String,Object> agentShop = agentShopClient.getShopByAgentId(agentUser.get("id").toString());
        if(EmptyUtils.isNotEmpty(agentShop)){
            agentUser.put("shopid",agentShop.get("id").toString());
        }
        Map<String,Object> area =  sysDtAreaClient.getSysDtAreaById(agentUser.get("agentArea").toString());
        agentUser.put("area_name",area.get("area_name").toString());
        Map<String,Object> areaf = sysDtAreaClient.getSysDtAreaById(agentUser.get("agentArea").toString());
        Map<String,Object> areas = sysDtAreaClient.getSysDtAreaById(areaf.get("area_parent_id").toString());
        Map<String,Object> areat = sysDtAreaClient.getSysDtAreaById(areas.get("area_parent_id").toString());
        String areaAdd = areaf.get("area_name").toString();
        if(EmptyUtils.isNotEmpty(areas)){
            areaAdd = areas.get("area_name").toString() +" "+areaAdd;
        }
        if(EmptyUtils.isNotEmpty(areat)){
            areaAdd = areat.get("area_name").toString() +" "+areaAdd;
        }
        agentUser.put("areaAdd",areaAdd);
        return agentUser;
    }

    @Override
    public Dto agentDologin(HttpServletRequest request) throws Exception{
        String phone = request.getParameter("phone");
        String yzCode = request.getParameter("yzCode");
        if("15538218507".equals(phone) || "15538218507".equals(yzCode)){
//            Map<String,Object>   user = agentUserClient.getAgentUserByPhone(phone);
            Map<String,Object>   user = getAgentUserByPhone(phone);
            user.put("devoCode",request.getHeader("code"));
            String token = agentUserClient.createAgentToken(request.getHeader("agent"), user);
            agentUserClient.saveAgentToken(token, user);
            //返回TokenVO
            TokenVO tokenVO = new TokenVO(token,
                    Calendar.getInstance().getTimeInMillis() + 2*60*60 * 1000,//2h有效期
                    Calendar.getInstance().getTimeInMillis());
            Map<String,Object> map =new HashMap<String,Object>();
            map.put("user",user);
            map.put("token",tokenVO);
            return DtoUtil.returnDataSuccess(map);
        }

            if(EmptyUtils.isEmpty(redisUtils.get(phone))){
                return  DtoUtil.returnFail("验证码已失效","002");
            }
            if(!yzCode.equals(redisUtils.get(phone))){
                return  DtoUtil.returnFail("输入验证码有误","002");
            }
            Map<String,Object> user = null;
            if(EmptyUtils.isNotEmpty(phone)){
                user = getAgentUserByPhone(phone);
            }else{
                return DtoUtil.returnFail("手机号为空", "002");
            }
            if (EmptyUtils.isNotEmpty(user)) {
                if("0".equals(user.get("valid_state").toString())){
                    return DtoUtil.returnFail("账号已失效，请联系客服处理","002");
                }
                user.put("devoCode",request.getHeader("code"));
                String token = agentUserClient.createAgentToken(request.getHeader("agent"), user);
                agentUserClient.saveAgentToken(token, user);
                TokenVO tokenVO = new TokenVO(token,
                        Calendar.getInstance().getTimeInMillis() + 2*60*60 * 1000,//2h有效期
                        Calendar.getInstance().getTimeInMillis());
                Map<String,Object> map =new HashMap<String,Object>();
                map.put("user",user);
                map.put("token",tokenVO);
                return DtoUtil.returnDataSuccess(map);
            } else {
                return DtoUtil.returnFail("手机号不存在", "002");
            }
    }

    @Override
    public Dto agentProfit(HttpServletRequest request) throws Exception{
        String token = request.getHeader("token");
        Map<String,Object> agentUser =  JSON.parseObject(redisUtils.getString(token), Map.class);
        Map<String,Object> user = agentUserClient.getAgentUserByPhone(agentUser.get("phone").toString());
        Map<String,Object> retMap =new HashMap<String, Object>();
        Map<String,Object> param = new HashMap<String,Object>();
        param.put("id",user.get("id").toString());
        param.put("code",user.get("invitation_code").toString());
        param.put("level",user.get("level").toString());
        if("1".equals(user.get("level").toString())){
            String createTime = user.get("createDate").toString();
            String begTime = DateUtil.format(new Date(),"yyyy-MM-dd")+" 00:00:00";
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date startTime= sdf.parse(begTime);
            Date endTime= sdf.parse(createTime);
            if (startTime.getTime() < endTime.getTime()) {
                param.put("create_time",user.get("createDate").toString());
            }
        }
        param.put("type","1");
        String todayEar = agentUserForOrderDB.getTodayEar(param);
        param.put("type","2");
        String currentEar = agentUserForOrderDB.getTodayEar(param);
        param.put("type","3");
        String AllEar  = agentUserForOrderDB.getTodayEar(param);
        retMap.put("todayEar",todayEar == null?0:todayEar);
        retMap.put("currentEar",currentEar== null?0:currentEar);
        retMap.put("AllEar",AllEar== null?0:AllEar);
        List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
        String dateType = request.getParameter("dateType");
        String time = DateUtil.format(new Date(),"yyyy-MM-dd");
        if(EmptyUtils.isNotEmpty(dateType)){
            if("day".equals(dateType)){
                param.put("begTime",time+" 00:00:00");
                param.put("endTime",time+" 23:59:59");
            }
            if("mon".equals(dateType)){
                time = DateUtil.format(new Date(),"MM");
                String timeStr[] = DateUtil.getThisMonth(time).split(":");
                param.put("begTime",timeStr[0]+" 00:00:00");
                param.put("endTime",timeStr[1]+" 23:59:59");
            }
            if("yea".equals(dateType)){
                time = DateUtil.format(new Date(),"yyyy");
                param.put("begTime",time+"-01-01 00:00:00");
                param.put("endTime",time+"-12-31 23:59:59");
            }
            if("wek".equals(dateType)){
                String timeStr[] = DateUtil.getThisWeek(time).split(":");
                param.put("begTime",timeStr[0]+" 00:00:00");
                param.put("endTime",timeStr[1]+" 23:59:59");
            }
        }else{
            param.put("type","wek");
            String timeStr[] = DateUtil.getThisWeek(time).split(":");
            param.put("begTime",timeStr[0]+" 00:00:00");
            param.put("endTime",timeStr[1]+" 23:59:59");
        }

        String[] s = new String[7];
        if("1".equals(user.get("level").toString())){
            list = agentUserClient.getAgentUsersByParentInviCode(user.get("invitation_code").toString());
            for(Map<String,Object> agent: list){
                Map<String,Object> area = sysDtAreaClient.getSysDtAreaById(agent.get("agent_area").toString());
                agent.put("area_name",area.get("area_name").toString());
                List<String> aresIds =  agentUserForUserDB.getAllAreaByPid(agent.get("agent_area").toString());
                String ids = "";
                for(String str:aresIds){
                    ids = ids + str +",";
                }
                ids = ids.substring(0,ids.length()-1);
                param.put("ids",ids.split(","));
                String earning = agentUserForOrderDB.getAllEarning(param);
                if(EmptyUtils.isEmpty(earning)){
                    earning = "0";
                }
                agent.put("earning",earning);
            }
            Collections.sort(list, new Comparator<Map<String, Object>>(){
                public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                    String name1 =(String)o1.get("earning");//name1是从你list里面拿出来的一个
                    String name2= (String)o2.get("earning"); //name1是从你list里面拿出来的第二个name
                    return name2.compareTo(name1);
                }
            });
        }else{
            List<String> aresIds =  agentUserForUserDB.getAllAreaByPid(user.get("agentArea").toString());
            String ids = "";
            for(String str:aresIds){
                ids = ids + str +",";
            }
            ids = ids.substring(0,ids.length()-1);
            param.put("dateType",dateType);
            param.put("ids",ids.split(","));
            Map<String,Object> levelBMap = new HashMap<String,Object>();
            List<Map<String,Object>> profitList =  agentUserForOrderDB.getProfitOfLevlB(param);
            levelBMap =  profitList.get(0);
            if("wek".equals(dateType)){
                s = new String[7];
            }
            if("mon".equals(dateType)){
                    s = new String[31];
                }
                if("day".equals(dateType)){
                    s = new String[24];
                }
                if("yea".equals(dateType)){
                    s = new String[12];
                }

            if(EmptyUtils.isNotEmpty(levelBMap)){
                for(String key : levelBMap.keySet()){
                    for(int co = 1;co<s.length+1;co++){
                        if(String.format("%02d", co).equals(key)){
                            s[co-1] = levelBMap.get(key).toString();
                            break;
                        }
                    }
                }
                for(int n =0;n<s.length;n++){
                    Map<String,Object> m = new HashMap<String, Object>();
                    m.put("data",String.format("%02d", n+1)+":"+s[n]);
                    list.add(m);
                }
            }else{
                for(int n =0;n<s.length;n++){
                    Map<String,Object> m = new HashMap<String, Object>();
                    m.put("data",String.format("%02d", n+1)+":0");
                    list.add(m);
                }
            }
        }
        retMap.put("list",list);
        return  DtoUtil.returnDataSuccess(retMap);
    }

    @Override
    public Dto getRank(HttpServletRequest request) throws Exception{
        String token = request.getHeader("token");
        Map<String,Object> agentUser =  JSON.parseObject(redisUtils.getString(token), Map.class);
        Map<String,Object> user = agentUserClient.getAgentUserByPhone(agentUser.get("phone").toString());
        List<Map<String,Object>> agentUserList = agentUserClient.getAgentUsersByParentInviCode(user.get("parent_invitation_code").toString());
        Map<String,Object> selfRank = new HashMap<String, Object>();
        for(Map<String,Object> agent: agentUserList){
            Map<String,Object> area = sysDtAreaClient.getSysDtAreaById(agent.get("agent_area").toString());
            agent.put("area_name",area.get("area_name").toString());
           List<String> aresIds =  agentUserForUserDB.getAllAreaByPid(agent.get("agent_area").toString());
           String ids = "";
           for(String str:aresIds){
               ids = ids + str +",";
           }
           ids = ids.substring(0,ids.length()-1);
            area.put("ids",ids.split(","));
            String earning = agentUserForOrderDB.getAllEarning(area);
            if(EmptyUtils.isEmpty(earning)){
                earning = "0";
            }
            agent.put("earning",earning);
            if(agentUser.get("id").equals(agent.get("id"))){
                selfRank = agent;
            }
        }
        Collections.sort(agentUserList, new Comparator<Map<String, Object>>(){
            public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                String name1 =(String)o1.get("earning");//name1是从你list里面拿出来的一个
                String name2= (String)o2.get("earning"); //name1是从你list里面拿出来的第二个name
                return name2.compareTo(name1);
            }
        });
        for(int n =0;n<agentUserList.size();n++){
            agentUserList.get(n).put("rank_no",n+1);
        }
        Map<String,Object> retMap = new HashMap<String, Object>();
        retMap.put("self_rank",selfRank);
        retMap.put("rankList",agentUserList);
        return  DtoUtil.returnDataSuccess(retMap);
    }
    @Override
    public Dto getAgentManageAreas(HttpServletRequest request) {
        String token = request.getHeader("token");
        Map<String,Object> agentUser =  JSON.parseObject(redisUtils.getString(token), Map.class);
        List<Map<String,Object>> areas = agentUserClient.getAgentAreasByAgentUserId(agentUser.get("id").toString());
        String sarea ="";
        for(Map<String,Object> area :areas){
            sarea = sarea +area.get("agent_area").toString()+",";
        }
        if(EmptyUtils.isNotEmpty(sarea)){
            sarea = sarea.substring(0,sarea.length()-1);
        }
        String pid = request.getParameter("area_parent_id");
        List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
        Map<String,Object> param = new HashMap<String, Object>();
        param.put("id",agentUser.get("id").toString());
        if(EmptyUtils.isNotEmpty(pid)){
            param.put("pid",pid);
        }
        param.put("areas",sarea.split(","));
        list = sysDtAreaClient.getAgentManageProAreas(param);
        Map<String,Object> retMap = new HashMap<String, Object>();
        retMap.put("list1",list);
        return DtoUtil.returnDataSuccess(retMap);
    }

    @Override
    public Dto getAgentEarList(HttpServletRequest request) throws Exception{
        String token = request.getHeader("token");
        Map<String,Object> agentUser =  JSON.parseObject(redisUtils.getString(token), Map.class);
        Map<String,Object> user = agentUserClient.getAgentUserByPhone(agentUser.get("phone").toString());
        String type= request.getParameter("type");
        Map<String,Object> param = new HashMap<String, Object>();
        param.put("type",type);
        param.put("code",user.get("invitation_code").toString());
        param.put("level",user.get("level").toString());
        List<Map<String,Object>> list = null;
        if("1".equals(type)){
            String begTime = request.getParameter("begTime");
            String endTime = request.getParameter("endTime");
            if(EmptyUtils.isNotEmpty(begTime) && EmptyUtils.isNotEmpty(endTime)){
                begTime = begTime + " 00:00:00";
                endTime = endTime + " 23:59:59";
                param.put("begTime",begTime);
                param.put("endTime",endTime);
            }else{
                param.put("begTime",DateUtil.format(new Date(),"yyyy-MM-dd")+" 00:00:00");
                param.put("endTime",DateUtil.format(new Date(),"yyyy-MM-dd")+" 23:59:59");
            }
        }
        if("2".equals(type)){
            List<Map<String,Object>> setList = agentUserClient.getSetOrderList(user.get("id").toString());
            String ids = "";
            for(Map<String,Object> map:setList){
                ids = ids + map.get("rep_order_id") +",";
            }
            if(EmptyUtils.isNotEmpty(ids)){
                ids = ids.substring(0,ids.length()-1);
                param.put("ids",ids);
            }
        }
        if("1".equals(user.get("level").toString())){
            param.put("id",user.get("id").toString());
            String area = request.getParameter("area");
            list =  agentUserForOrderDB.getAgentEarList(param);
            if(EmptyUtils.isNotEmpty(area)){
                List<Map<String,Object>> newList = new ArrayList<Map<String,Object>>();
                for(Map<String,Object> order :list){
                    if(area.equals(order.get("areaId").toString())){
                        newList.add(order);
                    }
                }
                list = newList;
            }
        }
        if("2".equals(user.get("level").toString())){
            param.put("id",user.get("id").toString());
            if(!"1".equals(type)){
                param.put("create_time",user.get("pay_time").toString());
            }
            list =  agentUserForOrderDB.getAgentEarList(param);
        }
        if(EmptyUtils.isNotEmpty(list)){
            Map<String,Object> retmap=new HashMap<String,Object>();
            BigDecimal bd = new BigDecimal("0");
            for(Map<String,Object> syMap : list){
                String areaName = getPCareaContent(syMap.get("areaId").toString());
                syMap.put("area_name",areaName);
                RepairUser repairUser = repairUserClient.getRepairUserById(syMap.get("user_id").toString());
                syMap.put("nickname",repairUser.getNickname());
                BigDecimal b1 = new BigDecimal(syMap.get("earning").toString());
                bd = b1.add(bd);
            }
            retmap.put("countMoney",bd.floatValue());
            retmap.put("list",list);
            return  DtoUtil.returnDataSuccess(retmap);
        }else{
            return DtoUtil.returnFail("没有收益列表","002");
        }
    }

    @Override
    public Dto getRepOrderDetail(HttpServletRequest request) throws Exception{
        String token = request.getHeader("token");
        Map<String,Object> agentUser =  JSON.parseObject(redisUtils.getString(token), Map.class);
        String id  = request.getParameter("id");
        String agent_level = agentUser.get("level").toString();
        Map<String,Object> param = new HashMap<String,Object>();
        param.put("id",id);param.put("agent_level",agent_level);
        Map<String,Object> order = agentUserForOrderDB.getRepOrderDetail(param);
        if(EmptyUtils.isNotEmpty(order)){
            String areaId= order.get("areaId").toString();
            order.put("area_name",getPCareaContent(areaId));
            return DtoUtil.returnDataSuccess(order);
        }else{
            return DtoUtil.returnFail("没有找到订单详情","002");
        }
    }

    public String getPCareaContent(String areaId) throws Exception{
        Map<String,Object> areaf = sysDtAreaClient.getSysDtAreaById(areaId);
        Map<String,Object> areas = sysDtAreaClient.getSysDtAreaById(areaf.get("area_parent_id").toString());
        Map<String,Object> areat = sysDtAreaClient.getSysDtAreaById(areas.get("area_parent_id").toString());
        return  areat.get("area_name")+" "+areas.get("area_name")+" "+areaf.get("area_name");
    }

    @Override
    public Dto getAgentInfo(HttpServletRequest request) throws Exception{
        String token = request.getHeader("token");
        Map<String,Object> agentUser =  JSON.parseObject(redisUtils.getString(token), Map.class);
        Map<String,Object> agent = agentUserClient.getAgentUserByPhone(agentUser.get("phone").toString());
        if(EmptyUtils.isNotEmpty(agent)){
            if(EmptyUtils.isNotEmpty(agent.get("end_time"))){
                if (Long.valueOf(agent.get("end_time").toString().replaceAll("-", "").replaceAll(":","").replaceAll(" ","")) < Long.valueOf(DateUtil.format(new Date(),"yyyy-MM-dd HH:mm:ss").toString().replaceAll("-", "").replaceAll(":","").replaceAll(" ",""))) {
                    agent.put("is_power","0");
                    agentUserClient.updateAgent(agent);
                }
            }
            return  DtoUtil.returnDataSuccess(agent);
        }else{
            return  DtoUtil.returnFail("没有找到此用户","002");
        }
    }

    @Override
    public Dto updateAgentInfo(HttpServletRequest request) throws Exception{
        String token = request.getHeader("token");
        Map<String,Object> agentUser =  JSON.parseObject(redisUtils.getString(token), Map.class);
        if(EmptyUtils.isEmpty(agentUser)){
            return DtoUtil.returnFail("用户未登录","001");
        }
        String yzCode = request.getParameter("yzCode");
        String phone =request.getParameter("phone");
        if(EmptyUtils.isNotEmpty(yzCode)){
            if(EmptyUtils.isEmpty(redisUtils.get(phone))){
                return  DtoUtil.returnFail("验证码已失效","002");
            }
            if(!yzCode.equals(redisUtils.get(phone))){
                return  DtoUtil.returnFail("输入验证码有误","002");
            }
            Map<String,Object> agnetMap =   agentUserClient.getAgentUserByPhone(phone);
            if(EmptyUtils.isNotEmpty(agnetMap)){
                return  DtoUtil.returnFail("此手机号已存在，不能更换为此手机号","002");
            }
        }
        String name =request.getParameter("name");
        String type_id =request.getParameter("type_id");
        String plan_id =request.getParameter("plan_id");
        String address =request.getParameter("address");
        String area =request.getParameter("area");
        String city =request.getParameter("city");
        String province =request.getParameter("province");
        String invitation_code =request.getParameter("invitation_code");
        String id_card =request.getParameter("id_card");
        String parent_invitation_code =request.getParameter("parent_invitation_code");
        Map<String,Object> agent = new HashMap<String,Object>();
        agent.put("id",agentUser.get("id").toString());
        if(EmptyUtils.isNotEmpty(name)){
            agent.put("name",name);
        }
        if(EmptyUtils.isNotEmpty(type_id)){
            agent.put("type_id",type_id);
        }
        if(EmptyUtils.isNotEmpty(plan_id)){
            agent.put("plan_id",plan_id);
        }
        if(EmptyUtils.isNotEmpty(address)){
            agent.put("address",address);
        }
        if(EmptyUtils.isNotEmpty(area)){
            agent.put("area",area);
        }
        if(EmptyUtils.isNotEmpty(city)){
            agent.put("city",city);
        }
        if(EmptyUtils.isNotEmpty(province)){
            agent.put("province",province);
        }
        if(EmptyUtils.isNotEmpty(invitation_code)){
            agent.put("invitation_code",invitation_code);
        }
        if(EmptyUtils.isNotEmpty(phone)){
            agent.put("phone",phone);
        }
        if(EmptyUtils.isNotEmpty(id_card)){
            agent.put("id_card",id_card);
        }
        if(EmptyUtils.isNotEmpty(parent_invitation_code)){
            agent.put("parent_invitation_code",parent_invitation_code);
        }
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
                request.getSession().getServletContext());
        // 判断是否有文件上传
        if (multipartResolver.isMultipart(request)){
            Map<String,Object> oldUser = agentUserClient.getAgentUserByPhone(agentUser.get("phone").toString());
            if(EmptyUtils.isNotEmpty(oldUser.get("image_url"))){
                String oldImg = oldUser.get("image_url").toString();
                String str = oldImg.substring(oldImg.indexOf("=")+1,oldImg.length());
                UploadUtil.deleteServerFile(str);
            }
            UploadInfo info = UploadUtil.fileUpload(request,"user/agentHeadImage/"+agent.get("id").toString());
            agent.put("image_url","https://www.zzzsyh.com/image/user/agentHeadImage/"+agent.get("id").toString()+"/"+info.getOldName());
        }
        int n = agentUserClient.updateAgent(agent);
        if(n>0){
            if(EmptyUtils.isNotEmpty(yzCode) && EmptyUtils.isNotEmpty(phone)){
                Map<String,Object>   user = getAgentUserByPhone(phone);
                user.put("devoCode",request.getHeader("code"));
                String newToken = agentUserClient.createAgentToken(request.getHeader("agent"), user);
                redisUtils.delete(token);
                agentUserClient.saveAgentToken(token, user);
                //返回TokenVO
                TokenVO tokenVO = new TokenVO(newToken,
                        Calendar.getInstance().getTimeInMillis() + 2*60*60 * 1000,//2h有效期
                        Calendar.getInstance().getTimeInMillis());
                Map<String,Object> map =new HashMap<String,Object>();
                map.put("user",user);
                map.put("token",tokenVO);
                return DtoUtil.returnDataSuccess(map);
            }else{
                return  DtoUtil.returnSuccess();
            }
        }else{
            return DtoUtil.returnFail("更改失败","002");
        }
    }

    @Override
    public Dto uploadAgentIdCard(HttpServletRequest request) throws Exception{
        String token = request.getHeader("token");
        Map<String,Object> user = JSON.parseObject(redisUtils.getString(token), Map.class);
        if(EmptyUtils.isNotEmpty(user)){
            user = agentUserClient.getAgentUserByPhone(user.get("phone").toString());
            String idCard = request.getParameter("id_card");
            String name = request.getParameter("name");
            if(EmptyUtils.isNotEmpty(idCard)){
                int n = agentUserClient.checkIdCardNum(idCard);
                if(n>0){
                    return DtoUtil.returnFail("此身份证已经注册过本APP，请换一个身份证","002");
                }
                List<UploadInfo> list = UploadUtil.uploadFiles(request,"","user/agentIdCardImg/"+user.get("id").toString());
                if(list.size() == 3){
                    String picUrl ="https://www.zzzsyh.com/image/user/agentIdCardImg/"+user.get("id").toString()+"/"+list.get(2).getOldName();
                    user.put("handHeldIdUrl",picUrl);
                }
                user.put("id_card",idCard);
                user.put("person",name);
                agentUserClient.updateAgent(user);
            }else{
                DtoUtil.returnFail("身份证号为空","002");
            }
            return  DtoUtil.returnSuccess();
        }else{
            return DtoUtil.returnFail("用户不存在","001");
        }
    }

    @Override
    public Dto registerAgentShop(HttpServletRequest request) throws Exception{
        String token = request.getHeader("token");
        Map<String,Object> agentUser =  JSON.parseObject(redisUtils.getString(token), Map.class);
        if(EmptyUtils.isEmpty(agentUser)){
            return DtoUtil.returnFail("用户未登录","001");
        }
        String dataStr = request.getParameter("data");
        Map<String,Object> shopInfo =  JSONObject.parseObject(dataStr);
        String agent_id = shopInfo.get("agent_id").toString();
        Map<String,Object> shop = agentUserForShopDB.getAgentShopByAgentId(agent_id);
        if(EmptyUtils.isEmpty(shop)){
            String id = IdWorker.getId();
            shopInfo.put("id",id);
            UploadInfo info= UploadUtil.fileUpload(request,"user/agentShopLogo/"+id);
            if(EmptyUtils.isNotEmpty(info)){
                shopInfo.put("shop_image","https://www.zzzsyh.com/image/user/agentShopLogo/"+id+"/"+info.getOldName());
                shopInfo.put("create_time",DateUtil.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
                agentUserForShopDB.insertAgentShop(shopInfo);
            }else{
                DtoUtil.returnFail("注册失败","002");
            }
            return DtoUtil.returnSuccess();
        }else{
            return  DtoUtil.returnSuccess();
        }
    }

    @Override
    public Dto actionPower(HttpServletRequest request) throws Exception{
        String token = request.getHeader("token");
        Map<String,Object> agentUser =  JSON.parseObject(redisUtils.getString(token), Map.class);
        if(EmptyUtils.isEmpty(agentUser)){
            return DtoUtil.returnFail("用户未登录","001");
        }
        String id =agentUser.get("id").toString();
        String money = "";
        List<Map<String,Object>> areas  = agentUserClient.getAgentAreasByAgentUserId(id);
        String area_level = areas.get(0).get("area_type").toString();
        if("A".equals(area_level)){
            money ="3000";
        }
        if("B".equals(area_level)){
            money ="2000";
        }
        if("C".equals(area_level)){
            money ="1000";
        }
        if(EmptyUtils.isEmpty(money)){
            return DtoUtil.returnFail("没有找到经销商管辖区域","002");
        }
        Map<String,Object> map =new HashMap<String, Object>();
        map.put("money",money);
        Calendar curr = Calendar.getInstance();
        curr.set(Calendar.YEAR,curr.get(Calendar.YEAR)+1);
        Date date=curr.getTime();
        map.put("date", DateUtil.format(date,"yyyy-MM-dd HH:mm:ss"));
        return DtoUtil.returnDataSuccess(map);
    }

    @Override
    public Dto powerInfo(HttpServletRequest request) {
        String token = request.getHeader("token");
        Map<String,Object> agentUser =  JSON.parseObject(redisUtils.getString(token), Map.class);
        if(EmptyUtils.isEmpty(agentUser)){
            return DtoUtil.returnFail("用户未登录","001");
        }
        List<Map<String,Object>> levelPayList = agentUserClient.getAgentLevelPays(agentUser.get("id").toString());
        Map<String,Object> levelPay = levelPayList.get(0);
        Map<String,Object> info = agentUserForUserDB.getInvoiceInfo(levelPay);
        if(EmptyUtils.isNotEmpty(levelPay)){
            if(EmptyUtils.isNotEmpty(info)){
                levelPay.put("invioceid",info.get("id").toString());
            }else{
                levelPay.put("invioceid","");
            }
            return DtoUtil.returnDataSuccess(levelPay);
        }else{
            return  DtoUtil.returnFail("没有找到入会信息","002");
        }
    }

    @Override
    public Dto invoiceInfo(HttpServletRequest request) {
        String token = request.getHeader("token");
        Map<String,Object> agentUser =  JSON.parseObject(redisUtils.getString(token), Map.class);
        if(EmptyUtils.isEmpty(agentUser)){
            return DtoUtil.returnFail("用户未登录","001");
        }
        List<Map<String,Object>> levelPayList = agentUserClient.getAgentLevelPays(agentUser.get("id").toString());
        Map<String,Object> levelPay = levelPayList.get(0);
        Map<String,Object> info = agentUserForUserDB.getInvoiceInfo(levelPay);
        if(EmptyUtils.isNotEmpty(info)){
            return DtoUtil.returnDataSuccess(info);
        }else{
            return  DtoUtil.returnFail("没有找到入会信息","002");
        }
    }
}
